package com.example.jetpackcomposelazycolumn.data.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.jetpackcomposelazycolumn.data.Repository
import com.example.jetpackcomposelazycolumn.models.Post
import java.lang.Exception

class PostPagingDataSource: PagingSource<Int, Post>() {

    override fun getRefreshKey(state: PagingState<Int, Post>) = 0

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Post> {
        val pageNumber = params.key ?: 0
        return try {
            val posts = Repository.getPets(pageNumber)
            LoadResult.Page(
                data = posts.posts,
                prevKey = if (pageNumber == 0) null else pageNumber - 1,
                nextKey = if (posts.page_number == posts.max_pages) null else pageNumber + 1
            )

        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}